<?php
declare (strict_types = 1);

namespace app\api\controller;
use app\api\controller\Base;
use app\common\model\Product as Productmodel;
use app\common\model\Advert;
use app\common\model\User;
use app\common\model\ProductCate;
use app\common\model\ProductOrder;
use app\common\model\ProductOrderList;

use \think\Request;

class Product extends Base
{
	//商品列表
	public function index(Request $request){

		$cate_id = $request->param("cate_id");
		$type = $request->param("type") == ''?'1':$request->param("type");

		$whe_advert = [];
		$whe_advert[] = ['type','=','1'];
		$advert = Advert::getAllList($whe_advert,'id,imgurl','sort desc,id desc');
		foreach ($advert as $key => &$val) {
			$val['imgurl'] = imageUrl($val['imgurl']);
		}
		//一级
		$w = [];
		$w[] = ['status','=','1'];
		$w[] = ['pid','=','0'];
		$cate = ProductCate::getAllList($w,'id,title',"sort desc,id desc");
		$ca = [];
		$ca[0]['id'] = '';
		$ca[0]['title'] = '全部';
		foreach($cate as $k=>$v){
			$ca[$k+1] = $v;
		}
		$cate = $ca;		

		$whe = [];
		$whe[] = ['status','=','1'];
		if(!empty($cate_id)){
			$whe[] = ['cate_id','=',$cate_id];
		}
		if($type==1){
			$order = "id desc";
		}elseif($type==2){
			$order = "integral desc,id desc";
		}elseif($type==3){
			$order = "integral asc,id desc";
		}elseif($type==4){
			$whe[] = ['integral','=',0];
			$order = "integral asc,id desc";
		}
		$field="id,title,imgurl,integral,money";		
		$data = Productmodel::getList($whe,$field,$order,$this->page);
		foreach($data['list'] as $k=>&$v){
			$v['imgurl'] = imageUrl($v['imgurl']);
		}
		$result = $data;
		return $this->renderSuccess("请求成功",compact('advert','cate','result'));
	}

	/**
	 * 商品详情
	 */
	public function detail(Request $request){
		$product_id = $request->param("product_id");

		$whe = [];
		$whe[] = ['id','=',$product_id];
		$whe[] = ['status','=','1'];
		$product = Productmodel::getInfo($whe,'*');
		$arr = [];
		$arr[] = imageUrl($product['imgurl']);
		$product['imgurl'] = $arr;
		$product['content'] = contentImage($product['content']);
		return $this->renderSuccess("请求成功",compact('product'));
	}

	/**
	 * 兑换
	 */
	public function order(Request $request){
		$product_id = $request->param("product_id");
		$num = $request->param("num");
		if($num < 1){
		    return $this->renderError("兑换数量最少1个");
		}
		$whe = [];
		$whe[] = ['id','=',$product_id];
		$whe[] = ['status','=','1'];
		$product = Productmodel::getInfo($whe,'id,title,imgurl,money,integral');
		$product['imgurl'] = imageUrl($product['imgurl']);
		$total_money = jisuan($num,$product['money'],'*',2);
		$total_integral = jisuan($num,$product['integral'],'*',2);

		$product['num'] = $num;
		$product['total_money'] = $total_money;
		$product['total_integral'] = $total_integral;
		$user = $this->getUser();
		$integral = $user['jifen'];
		return $this->renderSuccess("请求成功",compact('product',"integral"));
	}

	/**
	 * 开始兑换
	 */
	public function orderadd(Request $request){
		$product_id = $request->param("product_id");
		$num = $request->param("num");
		$province = $request->param("province");
		$city = $request->param("city");
		$county = $request->param("county");
		$address = $request->param("address");
		$name = $request->param("name");
		$mobile = $request->param("mobile");
		$remark = $request->param("remark");
		if(empty($province)){
			return $this->renderError("请输入收货省");
		}
		if(empty($city)){
			return $this->renderError("请输入收货市");
		}
		if(empty($county)){
			return $this->renderError("请输入收货县");
		}
		if(empty($address)){
			return $this->renderError("请输入收货地址");
		}
		if(empty($name)){
			return $this->renderError("请输入收货姓名");
		}
		if(empty($mobile)){
			return $this->renderError("请输入收货手机号");
		}
		if($num < 1){
		    return $this->renderError("兑换数量最少1个");
		}


		$user = $this->getUser();

		$whe = [];
		$whe[] = ['id','=',$product_id];
		$whe[] = ['status','=','1'];
		$product = Productmodel::getInfo($whe,'id,title,imgurl,money,integral,yunfei');
		$total_money = jisuan(jisuan($num,$product['money'],'*',2),$product['yunfei'],'+',2);
		$total_integral = jisuan($num,$product['integral'],'*',2);
		$arr = [];
		$order_num = create_order_number();
		$arr['user_id'] = $user['id'];
		$arr['order_num'] = $order_num;
		$arr['total_money'] = $total_money;
		$arr['total_integral'] = $total_integral;
		$arr['total_integral'] = $total_integral;
		$arr['status'] = 1;
		$arr['addtime'] = time();
		
		$arr['name'] = $name;
		$arr['mobile'] = $mobile;
		$arr['province'] = $province;
		$arr['city'] = $city;
		$arr['county'] = $county;
		$arr['address'] = $address;
		$arr['remark'] = $remark;
		if($user['jifen'] < $total_integral){
			return $this->renderError("您的积分余额不足");
		}

		$dd = ProductOrder::insertGetId($arr);
			//添加订单详情
			$row = [];
			$row['order_id'] = $dd;
			$row['order_num'] = $order_num;
			$row['product_id'] = $product_id;
			$row['title'] = $product['title'];
			$row['imgurl'] = $product['imgurl'];
			$row['money'] = $product['money'];
			$row['integral'] = $product['integral'];
			$row['num'] = $num;
			$row['status'] = 1;
			$row['addtime'] = time();
			$pl = ProductOrderList::insert($row);

		if($dd && $pl){
			if($total_money > 0){
				//需要调佣微信支付 唤起支付
				$pay = new \app\api\controller\Pay($this->app);
            	$data = $pay->pay($order_num,$product['title'],$user['openid'],4); 
            	return $this->renderSuccess("请求成功",json_decode($data,true));  
			}
				$notify = new \app\api\controller\Notify($this->app);
            	$data = $notify->order_update($order_num,4); 
            	if($data==1){
            	    $data = [];
            		$data['is_weixin'] = 2;
            		return $this->renderSuccess("兑换成功",$data);
            	} 
		}
	}

	/**
	 * 积分商城订单
	 */
	public function orderlist(Request $request){
		$user = $this->getUser();
		$type = $request->param('type') == ''?'1':$request->param('type');  //1全部 2待支付 3代发货 4待收货 5已完成
		$whe = [];
		if($type==1){

		}elseif($type==2){
			$whe[] = ['status','=','1'];
		}elseif($type==3){
			$whe[] = ['status','=','2'];
		}elseif($type==4){
			$whe[] = ['status','=','3'];
		}elseif($type==5){
			$whe[] = ['status','=','4'];
		}
		$whe[] = ['user_id','=',$user['id']];
		$field = "id,order_num,total_integral,total_money,status";
		$data = ProductOrder::getList($whe,$field,'id desc',$this->page);
		foreach($data['list'] as $k=>&$v){
			$product = ProductOrderList::getInfo(['order_id'=>$v['id']]);
			$v['title'] = $product['title'];
			$v['num'] = $product['num'];
			$v['imgurl'] = imageUrl($product['imgurl']);
		}
		return $this->renderSuccess("请求成功",$data);
	}

	/**
	 * 订单详情
	 */
	public function order_detail(Request $request){
		$user = $this->getUser();
		$order_id = $request->param("order_id");
		$whe = [];
		$whe[] = ['id','=',$order_id];
		$whe[] = ['user_id','=',$user['id']];
		$order = ProductOrder::getInfo($whe,'*');
		if(empty($order)){
			return $this->renderError("请求异常，请稍后重试");
		}
		$order_info = ProductOrderList::getInfo(['order_id'=>$order_id],'*');
		$order['imgurl'] = imageUrl($order_info['imgurl']);
		$order['title'] = $order_info['title'];
		$order['num'] = $order_info['num'];
		$order['money'] = $order_info['money'];
		$order['integral'] = $order_info['integral'];
		$order['addtime'] = date("Y-m-d H:i:s",$order['addtime']);
		if(!empty($order['pay_time'])){
			$order['pay_time'] = date("Y-m-d H:i:s",$order['pay_time']);
		}else{
			$order['pay_time'] = "暂无";
		}
		if(!empty($order['fa_time'])){
			$order['deliver_time'] = date("Y-m-d H:i:s",$order['fa_time']);
		}else{
			$order['deliver_time'] = "暂无";
		}
		if(!empty($order['end_time'])){
			$order['confirm_time'] = date("Y-m-d H:i:s",$order['end_time']);
		}else{
			$order['confirm_time'] = "暂无";
		}
		return $this->renderSuccess("请求成功",$order);

	}

	/**
	 * 立即支付
	 */
	public function orderpay(Request $request){
		$user = $this->getUser();
		$order_id = $request->param("order_id");
		$whe = [];
		$whe[] = ['id','=',$order_id];
		$order = ProductOrder::getInfo($whe,'*');
		if($order['status']!='1'){
			return $this->renderError("请求异常，请稍后重试");
		}
		if($order['total_money'] > 0){
			$arr = [];
			$arr['order_num'] = create_order_number();
			ProductOrder::where($whe)->update($arr);
			//需要调佣微信支付 唤起支付
        		$pay = new \app\api\controller\Pay($this->app);
        		$title=  ProductOrderList::where(['order_id'=>$order_id])->value("title");
            	$data = $pay->pay($arr['order_num'],$title,$user['openid'],4); 
            	return $this->renderSuccess("请求成功",json_decode($data,true));  
		}else{
			return $this->renderError("请求异常，请稍后重试");
		}
	}

	/**
	 * 
	 */
	public function order_cancel(Request $request){
		$user = $this->getUser();
		$order_id = $request->param("order_id");
		$whe = [];
		$whe[] = ['id','=',$order_id];
		$order = ProductOrder::getInfo($whe,'*');
		if($order['status']!='1'){
			return $this->renderError("该订单已支付，暂不能取消");
		}
		$arr = [];
		$arr['status'] = 5;
		$dd = $order->save($arr);
		if($dd){
			return $this->renderSuccess("订单取消成功");
		}
	}

	/**
	 * 确认收货
	 */
	public function over_order(Request $request){
		$user = $this->getUser();
		$order_id = $request->param("order_id");
		$whe = [];
		$whe[] = ['id','=',$order_id];
		$order = ProductOrder::getInfo($whe,'*');
		if($order['status']!='3'){
			return $this->renderError("请求异常，请稍后重试");
		}
		$arr = [];
		$arr['status'] = 4;
		$dd = $order->save($arr);
		if($dd){
			return $this->renderSuccess("确认收货成功");
		}
	}

    /**
	 * 查看物流信息
	 */
	public function express(Request $request){
		$user = $this->getUser();
		$order_id = $request->param("order_id");
		$whe = [];
		$whe[] = ['id','=',$order_id];
		$order = ProductOrder::getInfo($whe,'id,order_num,courier_number,courier_name,mobile');

		$order_info = ProductOrderList::getInfo(['order_id'=>$order_id],'*');
		$order['imgurl'] = imageUrl($order_info['imgurl']);
		
		$mobile = substr($order['mobile'],-4);
        $order['title'] = $order_info['title'];
        $order['num'] = $order_info['num'];
        $order['wuliu'] = $this->getcourier($order['courier_number'].':'.$mobile,$order['courier_name']);

        return $this->renderSuccess('请求成功',$order);
	}

	/**
     * 查询物流信息
     */
    public function getcourier($no,$express_name=''){
        $host = "https://kdcx.market.alicloudapi.com";
        $path = "/express";
        $method = "POST";
        $appcode = "5d7aefe1b4f548bbbc5cbdbfe4807f35";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "express_id=".$no."&express_name=".$express_name;
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }

        $out_put = curl_exec( $curl );
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        list($header, $body) = explode("\r\n\r\n", $out_put, 2);

        $body = json_decode($body,true);
        return $body;
        
    }
}